package sk.sodik.atomFilter;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import sk.sodik.atomFilter.feeds.EMF;
import sk.sodik.atomFilter.feeds.FeedFilter;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class AtomFilterServlet extends HttpServlet {
	private static final String REQ_USER = "user";
	private static final Logger log = Logger.getLogger(AtomFilterServlet.class
			.getName());

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		String requestURI = req.getRequestURI();

		if (user == null) {
			resp.sendRedirect(userService.createLoginURL(requestURI));
			return;
		}

		req.setAttribute(REQ_USER, user);

		String action = req.getParameter("action");

		if ("add".equals(action)) {
			log.fine("Add action");
			addFeed(req);
		}

		if ("del".equals(action)) {
			log.fine("Del action");
			delFeed(req);
		}

		// enumerate all feeds
		listFeeds(req);

		RequestDispatcher dispatcher = req.getRequestDispatcher("feedList.jsp");
		dispatcher.forward(req, resp);
	}

	private void delFeed(HttpServletRequest req) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			String key = req.getParameter("key");
			log.fine("Going to remove " + key);
			FeedFilter obj = em.find(FeedFilter.class, key);

			if (obj != null) {
				em.remove(obj);
				log.fine("Removed! ");
			} else {
				log.fine("Cannot find " + key);
			}
		} finally {
			em.close();
		}
	}

	private void listFeeds(HttpServletRequest req) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			// TODO introduce user dependency
			User user = getCurrentUser(req);

			Query q = em.createQuery("select from "
					+ FeedFilter.class.getName() + " where userId = :userId");
			q.setParameter("userId", user.getUserId());

			List list = q.getResultList();
			// repack to own list as the returned one is kind of cursor
			list = new LinkedList(list);

			req.setAttribute("feedList", list);
		} finally {
			em.close();
		}
	}

	private User getCurrentUser(HttpServletRequest req) {
		return (User) req.getAttribute(REQ_USER);
	}

	private void addFeed(HttpServletRequest req) {
		EntityManager em = EMF.get().createEntityManager();
		try {
			FeedFilter feed = new FeedFilter();
			feed.setKey(req.getParameter("name"), getCurrentUser(req)
					.getUserId());
			feed.url = req.getParameter("url");
			feed.filter = req.getParameter("filter");
			log.fine("Going to add " + feed);

			em.persist(feed);

			log.fine("Saved!");
		} finally {
			em.close();
		}
	}
}
